import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:wan_android_flutter/common/base/base_controller.dart';
import 'package:dio/dio.dart' as dio_form_data;
import 'package:wan_android_flutter/common/network/model/login_model.dart';
import 'package:wan_android_flutter/common/utils/eventbus/event_bus_param.dart';
import 'package:wan_android_flutter/common/utils/eventbus/event_bus_util.dart';
import 'package:wan_android_flutter/common/utils/mmkv/mmkv_key.dart';
import 'package:wan_android_flutter/common/utils/mmkv/mmkv_util.dart';

import '../../common/network/http_util.dart';
import '../../common/network/json_parse.dart';
import '../../common/utils/eventbus/event_bus_type.dart';
import 'login_state.dart';

class LoginLogic extends BaseController {
  final LoginState state = LoginState();

  TextEditingController userNameController = TextEditingController();
  FocusNode userNameFocusNode = FocusNode();
  TextEditingController pwdController = TextEditingController();
  FocusNode pwdFocusNode = FocusNode();

  @override
  void onInit() {
    super.onInit();
    userNameController.addListener(() {});
    pwdController.addListener(() {});
    userNameFocusNode.requestFocus();
  }

  Future<void> login() async {
    dio_form_data.FormData formData = dio_form_data.FormData.fromMap(
        {'username': userNameController.text, 'password': pwdController.text});
    final response = await httpUtil.post("/user/login", data: formData);
    if (response.statusCode == 200 && response.data is Map<String, dynamic>) {
      final loginModel = JsonParse.fromJsonMap<LoginModel>(response.data);
      if (loginModel != null) {
        if (response.headers.map.containsKey("set-cookie")) {
          var cookie = response.headers.map["set-cookie"]?.join(";") ?? "";
          MMKVUtil.instance.putString(MMKVKey.username, userNameController.text);
          MMKVUtil.instance.putString(MMKVKey.cookie, cookie);
          eventBusUtil.sentEvent(EventBusParam(EventBusType.refreshUserInfo, result: loginModel));
          Get.back();
        }
      }
    }
  }
}
